import spacy
from spacy.matcher import PhraseMatcher, Matcher

nlp = spacy.load("zh_core_web_sm")  # 中文用 zh_core_web_sm
matcher = Matcher(nlp.vocab)

# 适用于 "85mm" 这类写法，作为一个 token
pattern_focal = [
    {"TEXT": {"REGEX": r"^\d{2,3}$"}},
    {"LOWER": "mm"}
]
matcher.add("FOCAL_LENGTH", [pattern_focal])

# 适用于 "f/1.8"、"f2.8" 等光圈值（英文/中文均可扩展）
pattern_aperture = [
    {"LOWER": "f"},
    {"TEXT": "/"},
    {"TEXT": {"REGEX": r"^\d(\.\d)?$"}}
]
matcher.add("APERTURE", [pattern_aperture])

brands = [
    "Nikon", "尼康", "Canon", "佳能", "Sony", "索尼",
    "Fujifilm", "富士", "Sigma", "适马", "Tamron", "腾龙",
    "Tokina", "图丽", "Samyang", "三阳", "森养", "Pentax", "宾得",
    "Laowa", "老蛙"
]
brand_matcher = PhraseMatcher(nlp.vocab, attr="LOWER")
brand_patterns = [nlp.make_doc(brand) for brand in brands]
brand_matcher.add("BRAND", brand_patterns)

# 示例文本
doc = nlp("Nikon AF-S 85mm f/1.8 G 镜头")

for match_id, start, end in brand_matcher(doc):
    span = doc[start:end]
    print("品牌：", span.text)

# 匹配结果
matches = matcher(doc)
for match_id, start, end in matches:
    span = doc[start:end]
    print(nlp.vocab.strings[match_id], ":", span.text)
